package com.bc.plugin.doc.builder;

import com.bc.plugin.doc.resolver.help.JavaClassUtil;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocGlobalConstants;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import lombok.Getter;

import java.io.File;
import java.util.*;

public class JavaClassFileBuilder {
    @Getter
    private JavaProjectBuilder javaProjectBuilder;
    @Getter
    private Map<String, JavaClass> javaFilesMap;
    private List<String> paths;

    public JavaClassFileBuilder() {
        this(null);
    }

    public JavaClassFileBuilder(List<String> paths) {
        this.paths = paths;
        init();
    }

    private void init() {
        javaProjectBuilder = new JavaProjectBuilder();
        javaFilesMap = new HashMap<>();
        javaProjectBuilder.addSourceTree(new File(DocGlobalConstants.PROJECT_CODE_PATH));
        if (paths != null) {
            for (String path : paths) {
                if (null == path) {
                    continue;
                }
                if (StringUtil.isNotEmpty(path)) {
                    path = path.replace("\\", "/");
                    javaProjectBuilder.addSourceTree(new File(path));
                }
            }
        }
        Collection<JavaClass> javaClasses = javaProjectBuilder.getClasses();
        for (JavaClass cls : javaClasses) {
            javaFilesMap.put(cls.getFullyQualifiedName(), cls);
        }
    }

    public JavaClass getModelClassByName(String simpleName) {
        JavaClass cls = javaProjectBuilder.getClassByName(simpleName);
        List<JavaField> fieldList = JavaClassUtil.getFields(cls);
        // handle inner class
        if (Objects.isNull(cls.getFields()) || fieldList.isEmpty()) {
            cls = javaFilesMap.get(simpleName);
        } else {
            List<JavaClass> classList = cls.getNestedClasses();
            for (JavaClass javaClass : classList) {
                javaFilesMap.put(javaClass.getFullyQualifiedName(), javaClass);
            }
        }
        return cls;
    }

}
